Imports System.IO
Imports Aricie.DNN.Services
Imports Aricie.Services
Imports Lucene.Net.Analysis

Namespace Aricie.DNN.Modules.LuceneSearch.Business
    Public Class LocalizedSnowballAnalyzer
        Inherits SnowballAccentAnalyzer

#Region "ctor"

        Public Sub New(ByVal languageEnglishName As String)
            MyBase.New(languageEnglishName, GetStopWords(languageEnglishName))

        End Sub

#End Region

#Region "Private methods"

        Private Shared Function GetFileMapPath(ByVal languageEnglishName As String) As String
            Dim toReturn As String = "App_Data\" & languageEnglishName & ".stop"
            toReturn = System.IO.Path.Combine(GetModuleDirectoryMapPath(BusinessController.LuceneSearchResultsDefId), toReturn)
            Return toReturn
        End Function

        Private Shared Function ParseFile(ByVal fileName As String) As String()

            Dim toReturn As String() = {}

            If File.Exists(fileName) Then

                Dim fileLines As String() = File.ReadAllLines(fileName)
                Dim tempList As New List(Of String)
                For Each fileLine As String In fileLines
                    Dim stopWord As String = fileLine
                    Dim indexComment As Integer = fileLine.LastIndexOf("|"c)
                    If indexComment > 0 Then
                        stopWord = stopWord.Substring(0, indexComment)
                    End If
                    stopWord = stopWord.Trim().Trim("|"c)
                    If stopWord <> "" Then
                        tempList.Add(stopWord)
                    End If
                Next
                toReturn = tempList.ToArray

            End If

            Return toReturn

        End Function

        Private Shared Function GetStopWords(ByVal languageEnglishName As String) As String()

            Dim toReturn As String() = GetGlobal(Of String())("stopwords", languageEnglishName)
            If toReturn Is Nothing Then

                Dim filePath As String = GetFileMapPath(languageEnglishName)
                toReturn = ParseFile(filePath)

                SetGlobal(Of String())(toReturn, "stopwords", languageEnglishName)
            End If

            Return toReturn

        End Function

#End Region

    End Class

End Namespace